package com.trendata.util;

import java.io.File;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadUtil {

	private static int UPLOAD_BUFFERD_SIZE = 4096;// 缓冲区大小
	private static int UPLOAD_TEMP_FILE_SIZE = 4194304;// 临时文件大小
	private static String UPLOAD_TEMP_FILE_PATH = "/home/tomcat/tempUploadFile";

	/**
	 * 获取上传的文件
	 * 
	 * @param req
	 * @return 文件的fileItem
	 */
	public static List<FileItem> uploadImages(HttpServletRequest req) {
		List<FileItem> items = null;
		try {
			boolean isMultipart = ServletFileUpload.isMultipartContent(req);
			if (!isMultipart) {
				return null;
			}
			// 初始化
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(UPLOAD_BUFFERD_SIZE);
			File cachefilePath = new File(UPLOAD_TEMP_FILE_PATH);
			if (!cachefilePath.exists()) {
				cachefilePath.mkdirs();
			}
			factory.setRepository(cachefilePath);
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(UPLOAD_TEMP_FILE_SIZE);
			items = upload.parseRequest(req);
			for (int i = items.size()-1; i >= 0; i--) {
				FileItem item = items.get(i);
				if (item.isFormField()) {
					items.remove(i);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return items;
	}
}
